package com.afdor.rws.serialize.impl;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.serialize.Serialization;
import com.alibaba.fastjson.JSON;
import lombok.NonNull;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * FastJSON序列换实现
 *
 * @author 悭梵
 * @date Created in 2018-08-16 16:10
 */
@Extension(value = "fastjson", interfaceClass = Serialization.class)
public class FastjsonSerialization<IN> implements Serialization<IN, String> {
    @Override
    public String getContentType() {
        return "application/json;charset=utf-8;impl=fastjson";
    }

    @Override
    public String serialize(@NonNull IN data) {
        return JSON.toJSONString(data);
    }

    @Override
    public IN unserialize(@NonNull String data) {
        if (data == null || (data = data.trim()).length() == 0) {
            return null;
        }
        if (Objects.equals('[', data.charAt(0)) && Objects.equals(']', data.charAt(data.length() - 1))) {
            return (IN) JSON.parseArray(data);
        } else {
            ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
            return JSON.parseObject(data, type.getActualTypeArguments()[0]);
        }
    }

    public static void main(String[] args) {
        ArrayList<HashMap<Integer, String>> list = new ArrayList<HashMap<Integer, String>>(2);
        list.add(new HashMap<Integer, String>() {
            {
                put(10, "干什么");
                put(99, "脑壳有屎");
            }
        });

        list.add(new HashMap<Integer, String>() {
            {
                put(55, "笑死我了");
                put(159, "快点去睡吧");
            }
        });
        FastjsonSerialization<List<HashMap<Integer, String>>> serialization = new FastjsonSerialization<List<HashMap<Integer, String>>>();
        String json = serialization.serialize(list);

        List<HashMap<Integer, String>> newList = serialization.unserialize(json);

        System.out.println("相等: " + (list.equals(newList)));
    }
}
